package com.wl.blog.back.service.impl;

import com.wl.blog.back.bean.User;
import com.wl.blog.back.mapper.UserMapper;
import com.wl.blog.back.service.UserService;
import com.wl.blog.base.exception.BlogEnum;
import com.wl.blog.base.exception.BlogException;
import com.wl.blog.base.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @创建人 万磊
 * @创建时间 2021/12/3
 * 好好学习，天天向上
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user, String code, String rightCode) {
        //校验验证吗
        if (!rightCode.equalsIgnoreCase(code)){
            throw new BlogException(BlogEnum.USER_LOGIN_CODE);
        }

        //把用户输入的密码进行加密
        String password = user.getPassword();
        password = MD5Util.getMD5(password);
        user.setPassword(password);

        //校验用户名和密码是否正确
        List<User> users = userMapper.select(user);
//        System.out.println(users);
        if (users.size() == 0){
            throw new BlogException(BlogEnum.USER_LOGIN_ACCOUNT);
        }
        return users.get(0);
    }

    @Override
    public void verify01dPwd(String oldPwd, User user) {
        //加密输入的新密码
        oldPwd = MD5Util.getMD5(oldPwd);
        //获取用户原始登录密码
        String passowrd = user.getPassword();
        if (!passowrd.equals(oldPwd)){
            throw new BlogException(BlogEnum.USER_VERIFY_PASS);
        }
    }

    @Override
    public void updateUser(User user) {
        //给用户输入的新密码加密
        user.setPassword(MD5Util.getMD5(user.getPassword()));

        //根据主键更新非空字段
        //count：的记录数
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count == 0){
            throw new BlogException(BlogEnum.USER_UPDATE);
        }
    }

}
